<?php

namespace lanchain;

use think\Exception;
use think\facade\Log;

class LanchainHttp
{
    public static $_SUCCESS = '0000'; //http成功
    public static $_ERROR = '1000';

    /**
     * 短连接请求方法
     * $url：请求地址
     * $post_data：请求数据
     */
    public static function PostCURL($url, $post_data)
    {
        try{
            $ch         = curl_init();//初始化一个会话
            /* 设置验证方式 */
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//设置返回结果为流
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);//设置请求超时时间
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);//设置响应超时时间
            /* 设置通信方式 */
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);//使用urlencode格式请求

            $result = curl_exec($ch);//获取返回结果集
            $result = json_decode($result, true);//将返回结果集json格式解析转化为数组格式
            if (curl_errno($ch) !== 0) //网络问题请求失败
            {
                $result['result'] = self::$_ERROR;
                $result['msg'] = '网络请求超时';
                curl_close($ch);//关闭请求会话
                return $result;
            }else {
                $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                if ($statusCode != 200 || !isset($result['code']))//域名问题请求失败或不存在返回结果
                {
                    $result['msg'] = '网络请求失败';//清空result集合
                    $result['result'] = self::$_ERROR;
                }
                curl_close($ch);//关闭请求会话
                Log::record('======================stsrt  代还接口========================');
                Log::record($url);
                Log::record($post_data);
                Log::record($result);
                return $result;
            }
        }catch (Exception $e){
            $result['msg'] = '网络请求失败!';
            $result['result'] = self::$_SUCCESS;//返回http请求错误代码
            return $result;
        }
    }

}